package Tracker.server.control;

import java.security.NoSuchAlgorithmException;

import org.json.JSONException;
import org.json.JSONObject;

import com.sun.org.apache.xpath.internal.operations.Bool;

import Tracker.server.model.TError;
import Tracker.server.model.User;

public class UserController {
	ProtocolHandler handler;
	
	public UserController(ProtocolHandler h) {
		this.handler = h;
	}
	
	public void update(JSONObject req, JSONObject res) throws JSONException, NoSuchAlgorithmException {
		try {
			JSONObject u = req.getJSONObject("user");
			
			if(!u.isNull("id")) {
				if(u.getInt("id") == this.handler.session.user.id) {
					User user = this.handler.model.getUserById(u.getInt("id"));
					
					if(!u.isNull("name")) {
						user.setName(u.getString("name"));
					}
					
					if(!u.isNull("password")) {
						user.setPassword(u.getString("password"));
					}
					
					res.append("success", new Boolean(true));
					res.append("session", this.handler.session);
				} else {
					res.append("success", new Boolean(false));
					res.append("error", new TError("That 'aint you!", 401));
					return;
				}
			}
			
		} catch (JSONException e) {
			res.append("success", new Boolean(false));
			res.append("error", new TError("No user object", 400));
			return;
		}
	}
}
